home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / gnu / emacs.lha / emacs-19.16 / lisp / c-mode.el < prev    next >
Lisp/Scheme  |  1993-06-27  |  49KB  |  1,324 lines

  1. ;;; c-mode.el --- C code editing commands for Emacs
  2. ;; Copyright (C) 1985, 1986, 1987, 1992 Free Software Foundation, Inc.
  3.  
  4. ;; Maintainer: FSF
  5. ;; Keywords: c
  6.  
  7. ;; This file is part of GNU Emacs.
  8.  
  9. ;; GNU Emacs is free software; you can redistribute it and/or modify
  10. ;; it under the terms of the GNU General Public License as published by
  11. ;; the Free Software Foundation; either version 2, or (at your option)
  12. ;; any later version.
  13.  
  14. ;; GNU Emacs is distributed in the hope that it will be useful,
  15. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  17. ;; GNU General Public License for more details.
  18.  
  19. ;; You should have received a copy of the GNU General Public License
  20. ;; along with GNU Emacs; see the file COPYING.  If not, write to
  21. ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
  22.  
  23. ;;; Commentary:
  24.  
  25. ;; A smart editing mode for C code.  It knows a lot about C syntax and tries
  26. ;; to position the curser according to C layout conventions.  You can
  27. ;; change the details of the layout style with option variables.  Load it
  28. ;; and do M-x describe-mode for details.
  29.  
  30. ;;; Code:
  31.  
  32. (defvar c-mode-abbrev-table nil
  33.   "Abbrev table in use in C mode.")
  34. (define-abbrev-table 'c-mode-abbrev-table ())
  35.  
  36. (defvar c-mode-map ()
  37.   "Keymap used in C mode.")
  38. (if c-mode-map
  39.     ()
  40.   (setq c-mode-map (make-sparse-keymap))
  41.   (define-key c-mode-map "{" 'electric-c-brace)
  42.   (define-key c-mode-map "}" 'electric-c-brace)
  43.   (define-key c-mode-map ";" 'electric-c-semi)
  44.   (define-key c-mode-map "#" 'electric-c-sharp-sign)
  45.   (define-key c-mode-map ":" 'electric-c-terminator)
  46.   (define-key c-mode-map "\e\C-h" 'mark-c-function)
  47.   (define-key c-mode-map "\e\C-q" 'indent-c-exp)
  48.   (define-key c-mode-map "\ea" 'c-beginning-of-statement)
  49.   (define-key c-mode-map "\ee" 'c-end-of-statement)
  50.   (define-key c-mode-map "\eq" 'c-fill-paragraph)
  51.   (define-key c-mode-map "\C-c\C-n" 'c-forward-conditional)
  52.   (define-key c-mode-map "\C-c\C-p" 'c-backward-conditional)
  53.   (define-key c-mode-map "\C-c\C-u" 'c-up-conditional)
  54.   (define-key c-mode-map "\177" 'backward-delete-char-untabify)
  55.   (define-key c-mode-map "\t" 'c-indent-command))
  56.  
  57. ;; cmacexp is lame because it uses no preprocessor symbols.
  58. ;; It isn't very extensible either -- hardcodes /lib/cpp.
  59. (autoload 'c-macro-expand "cmacexp"
  60.   "Display the result of expanding all C macros occurring in the region.
  61. The expansion is entirely correct because it uses the C preprocessor."
  62.   t)
  63.  
  64. (defvar c-mode-syntax-table nil
  65.   "Syntax table in use in C-mode buffers.")
  66.  
  67. (if c-mode-syntax-table
  68.     ()
  69.   (setq c-mode-syntax-table (make-syntax-table))
  70.   (modify-syntax-entry ?\\ "\\" c-mode-syntax-table)
  71.   (modify-syntax-entry ?/ ". 14" c-mode-syntax-table)
  72.   (modify-syntax-entry ?* ". 23" c-mode-syntax-table)
  73.   (modify-syntax-entry ?+ "." c-mode-syntax-table)
  74.   (modify-syntax-entry ?- "." c-mode-syntax-table)
  75.   (modify-syntax-entry ?= "." c-mode-syntax-table)
  76.   (modify-syntax-entry ?% "." c-mode-syntax-table)
  77.   (modify-syntax-entry ?< "." c-mode-syntax-table)
  78.   (modify-syntax-entry ?> "." c-mode-syntax-table)
  79.   (modify-syntax-entry ?& "." c-mode-syntax-table)
  80.   (modify-syntax-entry ?| "." c-mode-syntax-table)
  81.   (modify-syntax-entry ?\' "\"" c-mode-syntax-table))
  82.  
  83. (defconst c-indent-level 2
  84.   "*Indentation of C statements with respect to containing block.")
  85. (defconst c-brace-imaginary-offset 0
  86.   "*Imagined indentation of a C open brace that actually follows a statement.")
  87. (defconst c-brace-offset 0
  88.   "*Extra indentation for braces, compared with other text in same context.")
  89. (defconst c-argdecl-indent 5
  90.   "*Indentation level of declarations of C function arguments.")
  91. (defconst c-label-offset -2
  92.   "*Offset of C label lines and case statements relative to usual indentation.")
  93. (defconst c-continued-statement-offset 2
  94.   "*Extra indent for lines not starting new statements.")
  95. (defconst c-continued-brace-offset 0
  96.   "*Extra indent for substatements that start with open-braces.
  97. This is in addition to c-continued-statement-offset.")
  98. (defconst c-style-alist
  99.   '(("GNU"
  100.      (c-indent-level               .  2)
  101.      (c-argdecl-indent             .  5)
  102.      (c-brace-offset               .  0)
  103.      (c-label-offset               . -2)
  104.      (c-continued-statement-offset .  2))
  105.     ("K&R"
  106.      (c-indent-level               .  5)
  107.      (c-argdecl-indent             .  0)
  108.      (c-brace-offset               . -5)
  109.      (c-label-offset               . -5)
  110.      (c-continued-statement-offset .  5))
  111.     ("BSD"
  112.      (c-indent-level               .  4)
  113.      (c-argdecl-indent             .  4)
  114.      (c-brace-offset               . -4)
  115.      (c-label-offset               . -4)
  116.      (c-continued-statement-offset .  4))
  117.     ("C++"
  118.      (c-indent-level               . 4)
  119.      (c-continued-statement-offset . 4)
  120.      (c-brace-offset               . -4)
  121.      (c-argdecl-indent             . 0)
  122.      (c-label-offset               . -4)
  123.      (c-auto-newline               . t))
  124.     ("Whitesmith"
  125.      (c-indent-level               .  4)
  126.      (c-argdecl-indent             .  4)
  127.      (c-brace-offset               .  0)
  128.      (c-label-offset               . -4)
  129.      (c-continued-statement-offset .  4))))
  130.  
  131. (defconst c-auto-newline nil
  132.   "*Non-nil means automatically newline before and after braces,
  133. and after colons and semicolons, inserted in C code.
  134. If you do not want a leading newline before braces then use:
  135.   (define-key c-mode-map \"{\" 'electric-c-semi)")
  136.  
  137. (defconst c-tab-always-indent t
  138.   "*Non-nil means TAB in C mode should always reindent the current line,
  139. regardless of where in the line point is when the TAB command is used.")
  140.  
  141. ;;; Regular expression used internally to recognize labels in switch
  142. ;;; statements.
  143. (defconst c-switch-label-regexp "case[ \t'/(]\\|default\\(\\S_\\|'\\)")
  144.  
  145.  
  146. (defun c-mode ()
  147.   "Major mode for editing C code.
  148. Expression and list commands understand all C brackets.
  149. Tab indents for C code.
  150. Comments are delimited with /* ... */.
  151. Paragraphs are separated by blank lines only.
  152. Delete converts tabs to spaces as it moves back.
  153. \\{c-mode-map}
  154. Variables controlling indentation style:
  155.  c-tab-always-indent
  156.     Non-nil means TAB in C mode should always reindent the current line,
  157.     regardless of where in the line point is when the TAB command is used.
  158.  c-auto-newline
  159.     Non-nil means automatically newline before and after braces,
  160.     and after colons and semicolons, inserted in C code.
  161.  c-indent-level
  162.     Indentation of C statements within surrounding block.
  163.     The surrounding block's indentation is the indentation
  164.     of the line on which the open-brace appears.
  165.  c-continued-statement-offset
  166.     Extra indentation given to a substatement, such as the
  167.     then-clause of an if or body of a while.
  168.  c-continued-brace-offset
  169.     Extra indentation given to a brace that starts a substatement.
  170.     This is in addition to c-continued-statement-offset.
  171.  c-brace-offset
  172.     Extra indentation for line if it starts with an open brace.
  173.  c-brace-imaginary-offset
  174.     An open brace following other text is treated as if it were
  175.     this far to the right of the start of its line.
  176.  c-argdecl-indent
  177.     Indentation level of declarations of C function arguments.
  178.  c-label-offset
  179.     Extra indentation for line that is a label, or case or default.
  180.  
  181. Settings for K&R and BSD indentation styles are
  182.   c-indent-level                5    8
  183.   c-continued-statement-offset  5    8
  184.   c-brace-offset               -5   -8
  185.   c-argdecl-indent              0    8
  186.   c-label-offset               -5   -8
  187.  
  188. Turning on C mode calls the value of the variable c-mode-hook with no args,
  189. if that value is non-nil."
  190.   (interactive)
  191.   (kill-all-local-variables)
  192.   (use-local-map c-mode-map)
  193.   (setq major-mode 'c-mode)
  194.   (setq mode-name "C")
  195.   (setq local-abbrev-table c-mode-abbrev-table)
  196.   (set-syntax-table c-mode-syntax-table)
  197.   (make-local-variable 'paragraph-start)
  198.   (setq paragraph-start (concat "^$\\|" page-delimiter))
  199.   (make-local-variable 'paragraph-separate)
  200.   (setq paragraph-separate paragraph-start)
  201.   (make-local-variable 'paragraph-ignore-fill-prefix)
  202.   (setq paragraph-ignore-fill-prefix t)
  203.   (make-local-variable 'indent-line-function)
  204.   (setq indent-line-function 'c-indent-line)
  205.   (make-local-variable 'indent-region-function)
  206.   (setq indent-region-function 'c-indent-region)
  207.   (make-local-variable 'require-final-newline)
  208.   (setq require-final-newline t)
  209.   (make-local-variable 'comment-start)
  210.   (setq comment-start "/* ")
  211.   (make-local-variable 'comment-end)
  212.   (setq comment-end " */")
  213.   (make-local-variable 'comment-column)
  214.   (setq comment-column 32)
  215.   (make-local-variable 'comment-start-skip)
  216.   (setq comment-start-skip "/\\*+ *")
  217.   (make-local-variable 'comment-indent-function)
  218.   (setq comment-indent-function 'c-comment-indent)
  219.   (make-local-variable 'parse-sexp-ignore-comments)
  220.   (setq parse-sexp-ignore-comments t)
  221.   (run-hooks 'c-mode-hook))
  222.  
  223. ;; This is used by indent-for-comment
  224. ;; to decide how much to indent a comment in C code
  225. ;; based on its context.
  226. (defun c-comment-indent ()
  227.   (if (looking-at "^/\\*")
  228.       0                ;Existing comment at bol stays there.
  229.     (let ((opoint (point)))
  230.       (save-excursion
  231.     (beginning-of-line)
  232.     (cond ((looking-at "[ \t]*}[ \t]*\\($\\|/\\*\\)")
  233.            ;; A comment following a solitary close-brace
  234.            ;; should have only one space.
  235.            (search-forward "}")
  236.            (1+ (current-column)))
  237.           ((or (looking-at "^#[ \t]*endif[ \t]*")
  238.            (looking-at "^#[ \t]*else[ \t]*"))
  239.            7)            ;2 spaces after #endif
  240.           ((progn
  241.          (goto-char opoint)
  242.          (skip-chars-backward " \t")
  243.          (and (= comment-column 0) (bolp)))
  244.            ;; If comment-column is 0, and nothing but space
  245.            ;; before the comment, align it at 0 rather than 1.
  246.            0)
  247.           (t
  248.            (max (1+ (current-column))    ;Else indent at comment column
  249.             comment-column)))))))    ; except leave at least one space.
  250.  
  251. (defun c-fill-paragraph (&optional arg)
  252.   "Like \\[fill-paragraph] but handle C comments.
  253. If any of the current line is a comment or within a comment,
  254. fill the comment or the paragraph of it that point is in,
  255. preserving the comment indentation or line-starting decorations."
  256.   (interactive "P")
  257.   (let* (comment-start-place
  258.      (first-line
  259.       ;; Check for obvious entry to comment.
  260.       (save-excursion
  261.         (beginning-of-line)
  262.         (skip-chars-forward " \t\n")
  263.         (and (looking-at comment-start-skip)
  264.          (setq comment-start-place (point))))))
  265.     (if (or first-line
  266.         ;; t if we enter a comment between start of function and this line.
  267.         (eq (calculate-c-indent) t)
  268.         ;; t if this line contains a comment starter.
  269.         (setq first-line
  270.           (save-excursion
  271.             (beginning-of-line)
  272.             (prog1
  273.             (re-search-forward comment-start-skip
  274.                        (save-excursion (end-of-line)
  275.                                (point))
  276.                        t)
  277.               (setq comment-start-place (point))))))
  278.     ;; Inside a comment: fill one comment paragraph.
  279.     (let ((fill-prefix
  280.            ;; The prefix for each line of this paragraph
  281.            ;; is the appropriate part of the start of this line,
  282.            ;; up to the column at which text should be indented.
  283.            (save-excursion
  284.          (beginning-of-line)
  285.          (if (looking-at "[ \t]*/\\*.*\\*/")
  286.              (progn (re-search-forward comment-start-skip)
  287.                 (make-string (current-column) ?\ ))
  288.            (if first-line (forward-line 1))
  289.  
  290.            (let ((line-width (progn (end-of-line) (current-column))))
  291.              (beginning-of-line)
  292.              (prog1
  293.              (buffer-substring
  294.               (point)
  295.  
  296.               ;; How shall we decide where the end of the
  297.               ;; fill-prefix is?
  298.               ;; calculate-c-indent-within-comment bases its value
  299.               ;; on the indentation of previous lines; if they're
  300.               ;; indented specially, it could return a column
  301.               ;; that's well into the current line's text.  So
  302.               ;; we'll take at most that many space, tab, or *
  303.               ;; characters, and use that as our fill prefix.
  304.               (let ((max-prefix-end
  305.                  (progn
  306.                    (move-to-column
  307.                     (calculate-c-indent-within-comment t)
  308.                     t)
  309.                    (point))))
  310.                 (beginning-of-line)
  311.                 (skip-chars-forward " \t*" max-prefix-end)
  312.                 (point)))
  313.  
  314.                ;; If the comment is only one line followed by a blank
  315.                ;; line, calling move-to-column above may have added
  316.                ;; some spaces and tabs to the end of the line; the
  317.                ;; fill-paragraph function will then delete it and the
  318.                ;; newline following it, so we'll lose a blank line
  319.                ;; when we shouldn't.  So delete anything
  320.                ;; move-to-column added to the end of the line.  We
  321.                ;; record the line width instead of the position of the
  322.                ;; old line end because move-to-column might break a
  323.                ;; tab into spaces, and the new characters introduced
  324.                ;; there shouldn't be deleted.
  325.  
  326.                ;; If you can see a better way to do this, please make
  327.                ;; the change.  This seems very messy to me.
  328.                (delete-region (progn (move-to-column line-width)
  329.                          (point))
  330.                       (progn (end-of-line) (point))))))))
  331.  
  332.           (paragraph-start
  333.            ;; Lines containing just a comment start or just an end
  334.            ;; should not be filled into paragraphs they are next to.
  335.            (concat 
  336.         paragraph-start
  337.         "\\|^[ \t]*/\\*[ \t]*$\\|^[ \t]*\\*/[ \t]*$\\|^[ \t/*]*$"))
  338.           (paragraph-separate
  339.            (concat
  340.         paragraph-separate
  341.         "\\|^[ \t]*/\\*[ \t]*$\\|^[ \t]*\\*/[ \t]*$\\|^[ \t/*]*$"))
  342.           (chars-to-delete 0))
  343.       (save-restriction
  344.         ;; Don't fill the comment together with the code following it.
  345.         ;; So temporarily exclude everything before the comment start,
  346.         ;; and everything after the line where the comment ends.
  347.         ;; If comment-start-place is non-nil, the comment starter is there.
  348.         ;; Otherwise, point is inside the comment.
  349.         (narrow-to-region (save-excursion
  350.                 (if comment-start-place
  351.                     (goto-char comment-start-place)
  352.                   (search-backward "/*"))
  353.                 ;; Protect text before the comment start 
  354.                 ;; by excluding it.  Add spaces to bring back 
  355.                 ;; proper indentation of that point.
  356.                 (let ((column (current-column)))
  357.                   (prog1 (point)
  358.                     (setq chars-to-delete column)
  359.                     (insert-char ?\  column))))
  360.                   (save-excursion
  361.                 (if comment-start-place
  362.                     (goto-char (+ comment-start-place 2)))
  363.                 (search-forward "*/" nil 'move)
  364.                 (forward-line 1)
  365.                 (point)))
  366.         
  367.         (fill-paragraph arg)
  368.         (save-excursion
  369.           ;; Delete the chars we inserted to avoid clobbering
  370.           ;; the stuff before the comment start.
  371.           (goto-char (point-min))
  372.           (if (> chars-to-delete 0)
  373.           (delete-region (point) (+ (point) chars-to-delete)))
  374.           ;; Find the comment ender (should be on last line of buffer,
  375.           ;; given the narrowing) and don't leave it on its own line.
  376.           (goto-char (point-max))
  377.           (forward-line -1)
  378.           (search-forward "*/" nil 'move)
  379.           (beginning-of-line)
  380.           (if (looking-at "[ \t]*\\*/")
  381.           (delete-indentation)))))
  382.       ;; Outside of comments: do ordinary filling.
  383.       (fill-paragraph arg))))
  384.  
  385. (defun electric-c-brace (arg)
  386.   "Insert character and correct line's indentation."
  387.   (interactive "P")
  388.   (let (insertpos)
  389.     (if (and (not arg)
  390.          (eolp)
  391.          (or (save-excursion
  392.            (skip-chars-backward " \t")
  393.            (bolp))
  394.          (if c-auto-newline (progn (c-indent-line) (newline) t) nil)))
  395.     (progn
  396.       (insert last-command-char)
  397.       (c-indent-line)
  398.       (if c-auto-newline
  399.           (progn
  400.         (newline)
  401.         ;; (newline) may have done auto-fill
  402.         (setq insertpos (- (point) 2))
  403.         (c-indent-line)))
  404.       (save-excursion
  405.         (if insertpos (goto-char (1+ insertpos)))
  406.         (delete-char -1))))
  407.     (if insertpos
  408.     (save-excursion
  409.       (goto-char insertpos)
  410.       (self-insert-command (prefix-numeric-value arg)))
  411.       (self-insert-command (prefix-numeric-value arg)))))
  412.  
  413. (defun electric-c-sharp-sign (arg)
  414.   "Insert character and correct line's indentation."
  415.   (interactive "P")
  416.   (if (save-excursion
  417.     (skip-chars-backward " \t")
  418.     (bolp))
  419.       (let ((c-auto-newline nil))
  420.     (electric-c-terminator arg))
  421.     (self-insert-command (prefix-numeric-value arg))))
  422.  
  423. (defun electric-c-semi (arg)
  424.   "Insert character and correct line's indentation."
  425.   (interactive "P")
  426.   (if c-auto-newline
  427.       (electric-c-terminator arg)
  428.     (self-insert-command (prefix-numeric-value arg))))
  429.  
  430. (defun electric-c-terminator (arg)
  431.   "Insert character and correct line's indentation."
  432.   (interactive "P")
  433.   (let (insertpos (end (point)))
  434.     (if (and (not arg) (eolp)
  435.          (not (save-excursion
  436.             (beginning-of-line)
  437.             (skip-chars-forward " \t")
  438.             (or (= (following-char) ?#)
  439.             ;; Colon is special only after a label, or case ....
  440.             ;; So quickly rule out most other uses of colon
  441.             ;; and do no indentation for them.
  442.             (and (eq last-command-char ?:)
  443.                  (not (looking-at c-switch-label-regexp))
  444.                  (save-excursion
  445.                    (skip-chars-forward "a-zA-Z0-9_$")
  446.                    (skip-chars-forward " \t")
  447.                    (< (point) end)))
  448.             (progn
  449.               (beginning-of-defun)
  450.               (let ((pps (parse-partial-sexp (point) end)))
  451.                 (or (nth 3 pps) (nth 4 pps) (nth 5 pps))))))))
  452.     (progn
  453.       (insert last-command-char)
  454.       (c-indent-line)
  455.       (and c-auto-newline
  456.            (not (c-inside-parens-p))
  457.            (progn
  458.          (newline)
  459.          ;; (newline) may have done auto-fill
  460.          (setq insertpos (- (point) 2))
  461.          (c-indent-line)))
  462.       (save-excursion
  463.         (if insertpos (goto-char (1+ insertpos)))
  464.         (delete-char -1))))
  465.     (if insertpos
  466.     (save-excursion
  467.       (goto-char insertpos)
  468.       (self-insert-command (prefix-numeric-value arg)))
  469.       (self-insert-command (prefix-numeric-value arg)))))
  470.  
  471. (defun c-inside-parens-p ()
  472.   (condition-case ()
  473.       (save-excursion
  474.     (save-restriction
  475.       (narrow-to-region (point)
  476.                 (progn (beginning-of-defun) (point)))
  477.       (goto-char (point-max))
  478.       (= (char-after (or (scan-lists (point) -1 1) (point-min))) ?\()))
  479.     (error nil)))
  480.  
  481. (defun c-indent-command (&optional whole-exp)
  482.   "Indent current line as C code, or in some cases insert a tab character.
  483. If `c-tab-always-indent' is non-nil (the default), always indent current line.
  484. Otherwise, indent the current line only if point is at the left margin or
  485. in the line's indentation; otherwise insert a tab.
  486.  
  487. A numeric argument, regardless of its value, means indent rigidly all the
  488. lines of the expression starting after point so that this line becomes
  489. properly indented.  The relative indentation among the lines of the
  490. expression are preserved."
  491.   (interactive "P")
  492.   (if whole-exp
  493.       ;; If arg, always indent this line as C
  494.       ;; and shift remaining lines of expression the same amount.
  495.       (let ((shift-amt (c-indent-line))
  496.         beg end)
  497.     (save-excursion
  498.       (if c-tab-always-indent
  499.           (beginning-of-line))
  500.       ;; Find beginning of following line.
  501.       (save-excursion
  502.         (forward-line 1) (setq beg (point)))
  503.       ;; Find first beginning-of-sexp for sexp extending past this line.
  504.       (while (< (point) beg)
  505.         (forward-sexp 1)
  506.         (setq end (point))
  507.         (skip-chars-forward " \t\n")))
  508.     (if (> end beg)
  509.         (indent-code-rigidly beg end shift-amt "#")))
  510.     (if (and (not c-tab-always-indent)
  511.          (save-excursion
  512.            (skip-chars-backward " \t")
  513.            (not (bolp))))
  514.     (insert-tab)
  515.       (c-indent-line))))
  516.  
  517. (defun c-indent-line ()
  518.   "Indent current line as C code.
  519. Return the amount the indentation changed by."
  520.   (let ((indent (calculate-c-indent nil))
  521.     beg shift-amt
  522.     (case-fold-search nil)
  523.     (pos (- (point-max) (point))))
  524.     (beginning-of-line)
  525.     (setq beg (point))
  526.     (cond ((eq indent nil)
  527.        (setq indent (current-indentation)))
  528.       ((eq indent t)
  529.        (setq indent (calculate-c-indent-within-comment)))
  530.       ((looking-at "[ \t]*#")
  531.        (setq indent 0))
  532.       (t
  533.        (skip-chars-forward " \t")
  534.        (if (listp indent) (setq indent (car indent)))
  535.        (cond ((or (looking-at c-switch-label-regexp)
  536.               (and (looking-at "[A-Za-z]")
  537.                (save-excursion
  538.                  (forward-sexp 1)
  539.                  (looking-at ":"))))
  540.           (setq indent (max 1 (+ indent c-label-offset))))
  541.          ((and (looking-at "else\\b")
  542.                (not (looking-at "else\\s_")))
  543.           (setq indent (save-excursion
  544.                  (c-backward-to-start-of-if)
  545.                  (current-indentation))))
  546.          ((looking-at "}[ \t]*else")
  547.           (setq indent (save-excursion
  548.                  (forward-char)
  549.                  (backward-sexp)
  550.                  (c-backward-to-start-of-if)
  551.                  (current-indentation))))
  552.          ((and (looking-at "while\\b")
  553.                (save-excursion
  554.              (c-backward-to-start-of-do)))
  555.           ;; This is a `while' that ends a do-while.
  556.           (setq indent (save-excursion
  557.                  (c-backward-to-start-of-do)
  558.                  (current-indentation))))
  559.          ((= (following-char) ?})
  560.           (setq indent (- indent c-indent-level)))
  561.          ((= (following-char) ?{)
  562.           (setq indent (+ indent c-brace-offset))))))
  563.     (skip-chars-forward " \t")
  564.     (setq shift-amt (- indent (current-column)))
  565.     (if (zerop shift-amt)
  566.     (if (> (- (point-max) pos) (point))
  567.         (goto-char (- (point-max) pos)))
  568.       (delete-region beg (point))
  569.       (indent-to indent)
  570.       ;; If initial point was within line's indentation,
  571.       ;; position after the indentation.  Else stay at same point in text.
  572.       (if (> (- (point-max) pos) (point))
  573.       (goto-char (- (point-max) pos))))
  574.     shift-amt))
  575.  
  576. (defun calculate-c-indent (&optional parse-start)
  577.   "Return appropriate indentation for current line as C code.
  578. In usual case returns an integer: the column to indent to.
  579. Returns nil if line starts inside a string, t if in a comment."
  580.   (save-excursion
  581.     (beginning-of-line)
  582.     (let ((indent-point (point))
  583.       (case-fold-search nil)
  584.       state
  585.       containing-sexp)
  586.       (if parse-start
  587.       (goto-char parse-start)
  588.     (beginning-of-defun))
  589.       (while (< (point) indent-point)
  590.     (setq parse-start (point))
  591.     (setq state (parse-partial-sexp (point) indent-point 0))
  592.     (setq containing-sexp (car (cdr state))))
  593.       (cond ((or (nth 3 state) (nth 4 state))
  594.          ;; return nil or t if should not change this line
  595.          (nth 4 state))
  596.         ((null containing-sexp)
  597.          ;; Line is at top level.  May be data or function definition,
  598.          ;; or may be function argument declaration.
  599.          ;; Indent like the previous top level line
  600.          ;; unless that ends in a closeparen without semicolon,
  601.          ;; in which case this line is the first argument decl.
  602.          (goto-char indent-point)
  603.          (skip-chars-forward " \t")
  604.          (if (= (following-char) ?{)
  605.          0   ; Unless it starts a function body
  606.            (c-backward-to-noncomment (or parse-start (point-min)))
  607.            ;; Look at previous line that's at column 0
  608.            ;; to determine whether we are in top-level decls
  609.            ;; or function's arg decls.  Set basic-indent accordingly.
  610.            (let ((basic-indent
  611.               (save-excursion
  612.             (re-search-backward "^[^ \^L\t\n#]" nil 'move)
  613.             (let (comment lim)
  614.               ;; Recognize the DEFUN macro in Emacs.
  615.               (if (save-excursion
  616.                 ;; Move down to the (putative) argnames line.
  617.                 (while (and (not (eobp))
  618.                         (not (looking-at " *[({}#/]")))
  619.                   (forward-line 1))
  620.                 ;; Go back to the DEFUN, if it is one.
  621.                 (condition-case nil
  622.                     (backward-sexp 1)
  623.                   (error))
  624.                 (beginning-of-line)
  625.                 (looking-at "DEFUN\\b"))
  626.                   c-argdecl-indent
  627.                 (if (and (looking-at "\\sw\\|\\s_")
  628.                      ;; This is careful to stop at the first
  629.                      ;; paren if we have
  630.                      ;; int foo Proto ((int, int));
  631.                      (looking-at "[^\"\n=(]*(")
  632.                      (progn
  633.                        (goto-char (1- (match-end 0)))
  634.                        (setq lim (point))
  635.                        (condition-case nil
  636.                        (forward-sexp 1)
  637.                      (error))
  638.                        (skip-chars-forward " \t\f")
  639.                        (and (< (point) indent-point)
  640.                         (not (memq (following-char)
  641.                                '(?\, ?\;)))))
  642.                      ;; Make sure the "function decl" we found
  643.                      ;; is not inside a comment.
  644.                      (progn
  645.                        (beginning-of-line)
  646.                        (while (and (not comment)
  647.                            (search-forward "/*" lim t))
  648.                      (setq comment
  649.                            (not (search-forward "*/" lim t))))
  650.                        (not comment)))
  651.                 c-argdecl-indent 0))))))
  652.          basic-indent)))
  653.  
  654. ;;          ;; Now add a little if this is a continuation line.
  655. ;;          (+ basic-indent (if (or (bobp)
  656. ;;                      (memq (preceding-char) '(?\) ?\; ?\}))
  657. ;;                      ;; Line with zero indentation
  658. ;;                      ;; is probably the return-type
  659. ;;                      ;; of a function definition,
  660. ;;                      ;; so following line is function name.
  661. ;;                      (= (current-indentation) 0))
  662. ;;                     0 c-continued-statement-offset))
  663.  
  664.         ((/= (char-after containing-sexp) ?{)
  665.          ;; line is expression, not statement:
  666.          ;; indent to just after the surrounding open.
  667.          (goto-char (1+ containing-sexp))
  668.          (current-column))
  669.         (t
  670.          ;; Statement level.  Is it a continuation or a new statement?
  671.          ;; Find previous non-comment character.
  672.          (goto-char indent-point)
  673.          (c-backward-to-noncomment containing-sexp)
  674.          ;; Back up over label lines, since they don't
  675.          ;; affect whether our line is a continuation.
  676.          (while (or (eq (preceding-char) ?\,)
  677.             (and (eq (preceding-char) ?:)
  678.                  (or (eq (char-after (- (point) 2)) ?\')
  679.                  (memq (char-syntax (char-after (- (point) 2)))
  680.                        '(?w ?_)))))
  681.            (if (eq (preceding-char) ?\,)
  682.            (progn (forward-char -1)
  683.               (c-backward-to-start-of-continued-exp containing-sexp)))
  684.            (beginning-of-line)
  685.            (c-backward-to-noncomment containing-sexp))
  686.          ;; Check for a preprocessor statement or its continuation lines.
  687.          ;; Move back to end of previous non-preprocessor line.
  688.          (let ((found (point)) stop)
  689.            (while (not stop)
  690.          (cond ((save-excursion (end-of-line 0)
  691.                     (= (preceding-char) ?\\))
  692.             (end-of-line 0))
  693.                ;; This line is not preceded by a backslash.
  694.                ;; So either it starts a preprocessor command
  695.                ;; or any following continuation lines
  696.                ;; should not be skipped.
  697.                ((progn (beginning-of-line) (= (following-char) ?#))
  698.             (end-of-line 0)
  699.             (setq found (point)))
  700.                (t (setq stop t))))
  701.            (goto-char found))
  702.          ;; Now we get the answer.
  703.          (if (and (not (memq (preceding-char) '(nil ?\, ?\; ?\} ?\{)))
  704.               ;; But don't treat a line with a close-brace
  705.               ;; as a continuation.  It is probably the
  706.               ;; end of an enum type declaration.
  707.               (save-excursion
  708.             (goto-char indent-point)
  709.             (skip-chars-forward " \t")
  710.             (not (= (following-char) ?}))))
  711.          ;; This line is continuation of preceding line's statement;
  712.          ;; indent  c-continued-statement-offset  more than the
  713.          ;; previous line of the statement.
  714.          (progn
  715.            (c-backward-to-start-of-continued-exp containing-sexp)
  716.            (+ c-continued-statement-offset (current-column)
  717.               (if (save-excursion (goto-char indent-point)
  718.                       (skip-chars-forward " \t")
  719.                       (eq (following-char) ?{))
  720.               c-continued-brace-offset 0)))
  721.            ;; This line starts a new statement.
  722.            ;; Position following last unclosed open.
  723.            (goto-char containing-sexp)
  724.            ;; Is line first statement after an open-brace?
  725.            (or
  726.          ;; If no, find that first statement and indent like it.
  727.          (save-excursion
  728.            (forward-char 1)
  729.            (let ((colon-line-end 0))
  730.              (while (progn (skip-chars-forward " \t\n")
  731.                    (looking-at "#\\|/\\*\\|case[ \t\n'/(].*:\\|[a-zA-Z0-9_$]*:"))
  732.                ;; Skip over comments and labels following openbrace.
  733.                (cond ((= (following-char) ?\#)
  734.                   (forward-line 1))
  735.                  ((= (following-char) ?\/)
  736.                   (forward-char 2)
  737.                   (search-forward "*/" nil 'move))
  738.                  ;; case or label:
  739.                  (t
  740.                   (save-excursion (end-of-line)
  741.                           (setq colon-line-end (point)))
  742.                   (search-forward ":"))))
  743.              ;; The first following code counts
  744.              ;; if it is before the line we want to indent.
  745.              (and (< (point) indent-point)
  746.               (- 
  747.                (if (> colon-line-end (point))
  748.                    (- (current-indentation) c-label-offset)
  749.                  (current-column))
  750.                ;; If prev stmt starts with open-brace, that
  751.                ;; open brace was offset by c-brace-offset.
  752.                ;; Compensate to get the column where
  753.                ;; an ordinary statement would start.
  754.                (if (= (following-char) ?\{) c-brace-offset 0)))))
  755.          ;; If no previous statement,
  756.          ;; indent it relative to line brace is on.
  757.          ;; For open brace in column zero, don't let statement
  758.          ;; start there too.  If c-indent-level is zero,
  759.          ;; use c-brace-offset + c-continued-statement-offset instead.
  760.          ;; For open-braces not the first thing in a line,
  761.          ;; add in c-brace-imaginary-offset.
  762.          (+ (if (and (bolp) (zerop c-indent-level))
  763.             (+ c-brace-offset c-continued-statement-offset)
  764.               c-indent-level)
  765.             ;; Move back over whitespace before the openbrace.
  766.             ;; If openbrace is not first nonwhite thing on the line,
  767.             ;; add the c-brace-imaginary-offset.
  768.             (progn (skip-chars-backward " \t")
  769.                (if (bolp) 0 c-brace-imaginary-offset))
  770.             ;; If the openbrace is preceded by a parenthesized exp,
  771.             ;; move to the beginning of that;
  772.             ;; possibly a different line
  773.             (progn
  774.               (if (eq (preceding-char) ?\))
  775.               (forward-sexp -1))
  776.               ;; Get initial indentation of the line we are on.
  777.               (current-indentation))))))))))
  778.  
  779. (defun calculate-c-indent-within-comment (&optional after-star)
  780.   "Return the indentation amount for line inside a block comment.
  781. Optional arg AFTER-STAR means, if lines in the comment have a leading star,
  782. return the indentation of the text that would follow this star."
  783.   (let (end star-start)
  784.     (save-excursion
  785.       (beginning-of-line)
  786.       (skip-chars-forward " \t")
  787.       (setq star-start (= (following-char) ?\*))
  788.       (skip-chars-backward " \t\n")
  789.       (setq end (point))
  790.       (beginning-of-line)
  791.       (skip-chars-forward " \t")
  792.       (if after-star
  793.       (and (looking-at "\\*")
  794.            (re-search-forward "\\*[ \t]*")))
  795.       (and (re-search-forward "/\\*[ \t]*" end t)
  796.        star-start
  797.        (not after-star)
  798.        (goto-char (1+ (match-beginning 0))))
  799.       (if (and (looking-at "[ \t]*$") (= (preceding-char) ?\*))
  800.       (1+ (current-column))
  801.     (current-column)))))
  802.  
  803.  
  804. (defun c-backward-to-noncomment (lim)
  805.   (let (opoint stop)
  806.     (while (not stop)
  807.       (skip-chars-backward " \t\n\f" lim)
  808.       (setq opoint (point))
  809.       (if (and (>= (point) (+ 2 lim))
  810.            (save-excursion
  811.          (forward-char -2)
  812.          (looking-at "\\*/")))
  813.       (search-backward "/*" lim 'move)
  814.     (setq stop (or (<= (point) lim)
  815.                (save-excursion
  816.              (beginning-of-line)
  817.              (skip-chars-forward " \t")
  818.              (not (looking-at "#")))))
  819.     (or stop (beginning-of-line))))))
  820.  
  821. (defun c-backward-to-start-of-continued-exp (lim)
  822.   (if (memq (preceding-char) '(?\) ?\"))
  823.       (forward-sexp -1))
  824.   (beginning-of-line)
  825.   (if (<= (point) lim)
  826.       (goto-char (1+ lim)))
  827.   (skip-chars-forward " \t"))
  828.  
  829. (defun c-backward-to-start-of-if (&optional limit)
  830.   "Move to the start of the last \"unbalanced\" `if'."
  831.   (or limit (setq limit (save-excursion (beginning-of-defun) (point))))
  832.   (let ((if-level 1)
  833.     (case-fold-search nil))
  834.     (while (and (not (bobp)) (not (zerop if-level)))
  835.       (backward-sexp 1)
  836.       (cond ((looking-at "else\\b")
  837.          (setq if-level (1+ if-level)))
  838.         ((looking-at "if\\b")
  839.          (setq if-level (1- if-level)))
  840.         ((< (point) limit)
  841.          (setq if-level 0)
  842.          (goto-char limit))))))
  843.  
  844. (defun c-backward-to-start-of-do (&optional limit)
  845.   "If point follows a `do' statement, move to beginning of it and return t.
  846. Otherwise return nil and don't move point."
  847.   (or limit (setq limit (save-excursion (beginning-of-defun) (point))))
  848.   (let ((first t)
  849.     (startpos (point))
  850.     (done nil))
  851.     (while (not done)
  852.       (let ((next-start (point)))
  853.     (condition-case nil
  854.         ;; Move back one token or one brace or paren group.
  855.         (backward-sexp 1)
  856.       ;; If we find an open-brace, we lose.
  857.       (error (setq done 'fail)))
  858.     (if done
  859.         nil
  860.       ;; If we reached a `do', we win.
  861.       (if (looking-at "do\\b")
  862.           (setq done 'succeed)
  863.         ;; Otherwise, if we skipped a semicolon, we lose.
  864.         ;; (Exception: we can skip one semicolon before getting
  865.         ;; to a the last token of the statement, unless that token
  866.         ;; is a close brace.)
  867.         (if (save-excursion
  868.           (forward-sexp 1)
  869.           (or (and (not first) (= (preceding-char) ?}))
  870.               (search-forward ";" next-start t
  871.                       (if (and first
  872.                            (/= (preceding-char) ?}))
  873.                       2 1))))
  874.         (setq done 'fail)
  875.           (setq first nil)
  876.           ;; If we go too far back in the buffer, we lose.
  877.           (if (< (point) limit)
  878.           (setq done 'fail)))))))
  879.     (if (eq done 'succeed)
  880.     t
  881.       (goto-char startpos)
  882.       nil)))
  883.  
  884. (defun c-beginning-of-statement (count)
  885.   "Go to the beginning of the innermost C statement.
  886. With prefix arg, go back N - 1 statements.  If already at the beginning of a
  887. statement then go to the beginning of the preceding one.
  888. If within a string or comment, or next to a comment (only whitespace between),
  889. move by sentences instead of statements."
  890.   (interactive "p")
  891.   (let ((here (point)) state)
  892.     (save-excursion
  893.       (beginning-of-defun)
  894.       (setq state (parse-partial-sexp (point) here nil nil)))
  895.     (if (or (nth 3 state) (nth 4 state)
  896.         (looking-at (concat "[ \t]*" comment-start-skip))
  897.         (save-excursion (skip-chars-backward " \t")
  898.                 (goto-char (- (point) 2))
  899.                 (looking-at "\\*/")))
  900.     (forward-sentence (- count))
  901.       (while (> count 0)
  902.     (c-beginning-of-statement-1)
  903.     (setq count (1- count)))
  904.       (while (< count 0)
  905.     (c-end-of-statement-1)
  906.     (setq count (1+ count))))))
  907.  
  908. (defun c-end-of-statement (count)
  909.   "Go to the end of the innermost C statement.
  910. With prefix arg, go forward N - 1 statements.
  911. Move forward to end of the next statement if already at end.
  912. If within a string or comment, move by sentences instead of statements."
  913.   (interactive "p")
  914.   (c-beginning-of-statement (- count)))
  915.  
  916. (defun c-beginning-of-statement-1 ()
  917.   (let ((last-begin (point))
  918.     (first t))
  919.     (condition-case ()
  920.     (progn
  921.       (while (and (not (bobp))
  922.               (progn
  923.             (backward-sexp 1)
  924.             (or first
  925.                 (not (re-search-forward "[;{}]" last-begin t)))))
  926.         (setq last-begin (point) first nil))
  927.       (goto-char last-begin))
  928.       (error (if first (backward-up-list 1) (goto-char last-begin))))))
  929.  
  930. (defun c-end-of-statement-1 ()
  931.   (condition-case ()
  932.       (progn
  933.     (while (and (not (eobp))
  934.             (let ((beg (point)))
  935.               (forward-sexp 1)
  936.               (let ((end (point)))
  937.             (save-excursion
  938.               (goto-char beg)
  939.               (not (re-search-forward "[;{}]" end t)))))))
  940.     (re-search-backward "[;}]")
  941.     (forward-char 1))
  942.     (error 
  943.      (let ((beg (point)))
  944.        (backward-up-list -1)
  945.        (let ((end (point)))
  946.      (goto-char beg)
  947.      (search-forward ";" end 'move))))))
  948.  
  949. (defun mark-c-function ()
  950.   "Put mark at end of C function, point at beginning."
  951.   (interactive)
  952.   (push-mark (point))
  953.   (end-of-defun)
  954.   (push-mark (point) nil t)
  955.   (beginning-of-defun)
  956.   (backward-paragraph))
  957.  
  958. (defun indent-c-exp (&optional endpos)
  959.   "Indent each line of the C grouping following point.
  960. If optional arg ENDPOS is given, indent each line, stopping when
  961. ENDPOS is encountered."
  962.   (interactive)
  963.   (let* ((indent-stack (list nil))
  964.      (opoint (point))  ;; May be altered below.
  965.      (contain-stack
  966.       (list (if endpos
  967.             (let (funbeg)
  968.               ;; Find previous fcn-start.
  969.               (save-excursion (forward-char 1)
  970.                       (beginning-of-defun)
  971.                       (setq funbeg (point)))
  972.               ;; Try to find containing open,
  973.               ;; but don't scan past that fcn-start.
  974.               (save-restriction
  975.             (narrow-to-region funbeg (point))
  976.             (condition-case nil
  977.                 (save-excursion
  978.                   (backward-up-list 1) (point))
  979.               ;; We gave up: must be between fcns.
  980.               ;; Set opoint to beg of prev fcn
  981.               ;; since otherwise calculate-c-indent
  982.               ;; will get wrong answers.
  983.               (error (setq opoint funbeg)
  984.                  (point)))))
  985.           (point))))
  986.      (case-fold-search nil)
  987.      restart outer-loop-done inner-loop-done state ostate
  988.      this-indent last-sexp
  989.      at-else at-brace at-while
  990.      last-depth
  991.      (next-depth 0))
  992.     ;; If the braces don't match, get an error right away.
  993.     (save-excursion
  994.       (forward-sexp 1))
  995.     ;; Realign the comment on the first line, even though we don't reindent it.
  996.     (save-excursion
  997.       (let ((beg (point)))
  998.     (and (re-search-forward
  999.           comment-start-skip
  1000.           (save-excursion (end-of-line) (point)) t)
  1001.          ;; Make sure the comment starter we found
  1002.          ;; is not actually in a string or quoted.
  1003.          (let ((new-state
  1004.             (parse-partial-sexp beg (point)
  1005.                     nil nil state)))
  1006.            (and (not (nth 3 new-state)) (not (nth 5 new-state))))
  1007.         (progn (indent-for-comment) (beginning-of-line)))))
  1008.     (save-excursion
  1009.       (setq outer-loop-done nil)
  1010.       (while (and (not (eobp))
  1011.           (if endpos (< (point) endpos)
  1012.             (not outer-loop-done)))
  1013.     (setq last-depth next-depth)
  1014.     ;; Compute how depth changes over this line
  1015.     ;; plus enough other lines to get to one that
  1016.     ;; does not end inside a comment or string.
  1017.     ;; Meanwhile, do appropriate indentation on comment lines.
  1018.     (setq inner-loop-done nil)
  1019.     (while (and (not inner-loop-done)
  1020.             (not (and (eobp) (setq outer-loop-done t))))
  1021.       (setq ostate state)
  1022.       (setq state (parse-partial-sexp (point) (progn (end-of-line) (point))
  1023.                       nil nil state))
  1024.       (setq next-depth (car state))
  1025.       (if (and (car (cdr (cdr state)))
  1026.            (>= (car (cdr (cdr state))) 0))
  1027.           (setq last-sexp (car (cdr (cdr state)))))
  1028.       (if (or (nth 4 ostate))
  1029.           (c-indent-line))
  1030.       (if (or (nth 3 state))
  1031.           (forward-line 1)
  1032.         (setq inner-loop-done t)))
  1033.     (and endpos
  1034.          (while (< next-depth 0)
  1035.            (setq indent-stack (append indent-stack (list nil)))
  1036.            (setq contain-stack (append contain-stack (list nil)))
  1037.            (setq next-depth (1+ next-depth))
  1038.            (setq last-depth (1+ last-depth))
  1039.            (setcar (nthcdr 6 state) (1+ (nth 6 state)))))
  1040.     (setq outer-loop-done (and (not endpos) (<= next-depth 0)))
  1041.     (if outer-loop-done
  1042.         nil
  1043.       ;; If this line had ..))) (((.. in it, pop out of the levels
  1044.       ;; that ended anywhere in this line, even if the final depth
  1045.       ;; doesn't indicate that they ended.
  1046.       (while (> last-depth (nth 6 state))
  1047.         (setq indent-stack (cdr indent-stack)
  1048.           contain-stack (cdr contain-stack)
  1049.           last-depth (1- last-depth)))
  1050.       (if (/= last-depth next-depth)
  1051.           (setq last-sexp nil))
  1052.       ;; Add levels for any parens that were started in this line.
  1053.       (while (< last-depth next-depth)
  1054.         (setq indent-stack (cons nil indent-stack)
  1055.           contain-stack (cons nil contain-stack)
  1056.           last-depth (1+ last-depth)))
  1057.       (if (null (car contain-stack))
  1058.           (setcar contain-stack (or (car (cdr state))
  1059.                     (save-excursion (forward-sexp -1)
  1060.                             (point)))))
  1061.       (forward-line 1)
  1062.       (skip-chars-forward " \t")
  1063.       (if (eolp)
  1064.           nil
  1065.         (if (and (car indent-stack)
  1066.              (>= (car indent-stack) 0))
  1067.         ;; Line is on an existing nesting level.
  1068.         ;; Lines inside parens are handled specially.
  1069.         (if (/= (char-after (car contain-stack)) ?{)
  1070.             (setq this-indent (car indent-stack))
  1071.           ;; Line is at statement level.
  1072.           ;; Is it a new statement?  Is it an else?
  1073.           ;; Find last non-comment character before this line
  1074.           (save-excursion
  1075.             (setq at-else (looking-at "else\\W"))
  1076.             (setq at-brace (= (following-char) ?{))
  1077.             (setq at-while (looking-at "while\\b"))
  1078.             (c-backward-to-noncomment opoint)
  1079.             (if (not (memq (preceding-char) '(nil ?\, ?\; ?} ?: ?{)))
  1080.             ;; Preceding line did not end in comma or semi;
  1081.             ;; indent this line  c-continued-statement-offset
  1082.             ;; more than previous.
  1083.             (progn
  1084.               (c-backward-to-start-of-continued-exp (car contain-stack))
  1085.               (setq this-indent
  1086.                 (+ c-continued-statement-offset (current-column)
  1087.                    (if at-brace c-continued-brace-offset 0))))
  1088.               ;; Preceding line ended in comma or semi;
  1089.               ;; use the standard indent for this level.
  1090.               (cond (at-else (progn (c-backward-to-start-of-if opoint)
  1091.                         (setq this-indent
  1092.                           (current-indentation))))
  1093.                 ((and at-while (c-backward-to-start-of-do opoint))
  1094.                  (setq this-indent (current-indentation)))
  1095.                 (t (setq this-indent (car indent-stack)))))))
  1096.           ;; Just started a new nesting level.
  1097.           ;; Compute the standard indent for this level.
  1098.           (let ((val (calculate-c-indent
  1099.                (if (car indent-stack)
  1100.                    (- (car indent-stack))
  1101.                  opoint))))
  1102.         (setcar indent-stack
  1103.             (setq this-indent val))))
  1104.         ;; Adjust line indentation according to its contents
  1105.         (if (or (looking-at c-switch-label-regexp)
  1106.             (and (looking-at "[A-Za-z]")
  1107.              (save-excursion
  1108.                (forward-sexp 1)
  1109.                (looking-at ":"))))
  1110.         (setq this-indent (max 1 (+ this-indent c-label-offset))))
  1111.         (if (= (following-char) ?})
  1112.         (setq this-indent (- this-indent c-indent-level)))
  1113.         (if (= (following-char) ?{)
  1114.         (setq this-indent (+ this-indent c-brace-offset)))
  1115.         ;; Don't leave indentation in empty lines.
  1116.         (if (eolp) (setq this-indent 0))
  1117.         ;; Put chosen indentation into effect.
  1118.         (or (= (current-column) this-indent)
  1119.         (= (following-char) ?\#)
  1120.         (progn
  1121.           (delete-region (point) (progn (beginning-of-line) (point)))
  1122.           (indent-to this-indent)))
  1123.         ;; Indent any comment following the text.
  1124.         (or (looking-at comment-start-skip)
  1125.         (let ((beg (point)))
  1126.           (and (re-search-forward
  1127.             comment-start-skip
  1128.             (save-excursion (end-of-line) (point)) t)
  1129.                ;; Make sure the comment starter we found
  1130.                ;; is not actually in a string or quoted.
  1131.                (let ((new-state
  1132.                   (parse-partial-sexp beg (point)
  1133.                           nil nil state)))
  1134.              (and (not (nth 3 new-state)) (not (nth 5 new-state))))
  1135.               (progn (indent-for-comment) (beginning-of-line)))))))))))
  1136.  
  1137. ;; Look at all comment-start strings in the current line after point.
  1138. ;; Return t if one of them starts a real comment.
  1139. ;; This is not used yet, because indent-for-comment
  1140. ;; isn't smart enough to handle the cases this can find.
  1141. (defun indent-c-find-real-comment ()
  1142.   (let (win)
  1143.     (while (and (not win)
  1144.         (re-search-forward comment-start-skip
  1145.                    (save-excursion (end-of-line) (point))
  1146.                    t))
  1147.       ;; Make sure the comment start is not quoted.
  1148.       (let ((state-1
  1149.          (parse-partial-sexp
  1150.           (save-excursion (beginning-of-line) (point))
  1151.           (point) nil nil state)))
  1152.     (setq win (and (null (nth 3 state-1)) (null (nth 5 state-1))))))
  1153.     win))
  1154.  
  1155. ;; Indent every line whose first char is between START and END inclusive.
  1156. (defun c-indent-region (start end)
  1157.   (save-excursion
  1158.     (goto-char start)
  1159.     (let ((endmark (copy-marker end)))
  1160.       (and (bolp) (not (eolp))
  1161.        (c-indent-line))
  1162.       (indent-c-exp endmark)
  1163.       (set-marker endmark nil))))
  1164.  
  1165. (defun set-c-style (style &optional global)
  1166.   "Set C-mode variables to use one of several different indentation styles.
  1167. The arguments are a string representing the desired style
  1168. and a flag which, if non-nil, means to set the style globally.
  1169. \(Interactively, the flag comes from the prefix argument.)
  1170. Available styles are GNU, K&R, BSD and Whitesmith."
  1171.   (interactive (list (completing-read "Use which C indentation style? "
  1172.                                       c-style-alist nil t)
  1173.              current-prefix-arg))
  1174.   (let ((vars (cdr (assoc style c-style-alist))))
  1175.     (or vars
  1176.     (error "Invalid C indentation style `%s'" style))
  1177.     (while vars
  1178.       (or global
  1179.       (make-local-variable (car (car vars))))
  1180.       (set (car (car vars)) (cdr (car vars)))
  1181.       (setq vars (cdr vars)))))
  1182.  
  1183. ;;; This page handles insertion and removal of backslashes for C macros.
  1184.  
  1185. (defvar c-backslash-column 48
  1186.   "*Minimum column for end-of-line backslashes of macro definitions.")
  1187.  
  1188. (defun c-backslash-region (from to delete-flag)
  1189.   "Insert, align, or delete end-of-line backslashes on the lines in the region.
  1190. With no argument, inserts backslashes and aligns existing backslashes.
  1191. With an argument, deletes the backslashes.
  1192.  
  1193. This function does not modify the last line of the region if the region ends 
  1194. right at the start of the following line; it does not modify blank lines
  1195. at the start of the region.  So you can put the region around an entire macro
  1196. definition and conveniently use this command."
  1197.   (interactive "r\nP")
  1198.   (save-excursion
  1199.     (goto-char from)
  1200.     (let ((column c-backslash-column)
  1201.       (endmark (make-marker)))
  1202.       (move-marker endmark to)
  1203.       ;; Compute the smallest column number past the ends of all the lines.
  1204.       (if (not delete-flag)
  1205.       (while (< (point) to)
  1206.         (end-of-line)
  1207.         (if (= (preceding-char) ?\\)
  1208.         (progn (forward-char -1)
  1209.                (skip-chars-backward " \t")))
  1210.         (setq column (max column (1+ (current-column))))
  1211.         (forward-line 1)))
  1212.       ;; Adjust upward to a tab column, if that doesn't push past the margin.
  1213.       (if (> (% column tab-width) 0)
  1214.       (let ((adjusted (* (/ (+ column tab-width -1) tab-width) tab-width)))
  1215.         (if (< adjusted (window-width))
  1216.         (setq column adjusted))))
  1217.       ;; Don't modify blank lines at start of region.
  1218.       (goto-char from)
  1219.       (while (and (< (point) endmark) (eolp))
  1220.     (forward-line 1))
  1221.       ;; Add or remove backslashes on all the lines.
  1222.       (while (and (< (point) endmark)
  1223.           ;; Don't backslashify the last line
  1224.           ;; if the region ends right at the start of the next line.
  1225.           (save-excursion
  1226.             (forward-line 1)
  1227.             (< (point) endmark)))
  1228.     (if (not delete-flag)
  1229.         (c-append-backslash column)
  1230.       (c-delete-backslash))
  1231.     (forward-line 1))
  1232.       (move-marker endmark nil))))
  1233.  
  1234. (defun c-append-backslash (column)
  1235.   (end-of-line)
  1236.   ;; Note that "\\\\" is needed to get one backslash.
  1237.   (if (= (preceding-char) ?\\)
  1238.       (progn (forward-char -1)
  1239.          (delete-horizontal-space)
  1240.          (indent-to column))
  1241.     (indent-to column)
  1242.     (insert "\\")))
  1243.  
  1244. (defun c-delete-backslash ()
  1245.   (end-of-line)
  1246.   (forward-char -1)
  1247.   (if (looking-at "\\\\")
  1248.       (delete-region (1+ (point))
  1249.              (progn (skip-chars-backward " \t") (point)))))
  1250.  
  1251. (defun c-up-conditional (count)
  1252.   "Move back to the containing preprocessor conditional, leaving mark behind.
  1253. A prefix argument acts as a repeat count.  With a negative argument,
  1254. move forward to the end of the containing preprocessor conditional.
  1255. When going backwards, `#elif' is treated like `#else' followed by `#if'.
  1256. When going forwards, `#elif' is ignored."
  1257.   (interactive "p")
  1258.   (c-forward-conditional (- count) t))
  1259.  
  1260. (defun c-backward-conditional (count &optional up-flag)
  1261.   "Move back across a preprocessor conditional, leaving mark behind.
  1262. A prefix argument acts as a repeat count.  With a negative argument,
  1263. move forward across a preprocessor conditional."
  1264.   (interactive "p")
  1265.   (c-forward-conditional (- count) up-flag))
  1266.  
  1267. (defun c-forward-conditional (count &optional up-flag)
  1268.   "Move forward across a preprocessor conditional, leaving mark behind.
  1269. A prefix argument acts as a repeat count.  With a negative argument,
  1270. move backward across a preprocessor conditional."
  1271.   (interactive "p")
  1272.   (let* ((forward (> count 0))
  1273.      (increment (if forward -1 1))
  1274.      (search-function (if forward 're-search-forward 're-search-backward))
  1275.      (opoint (point))
  1276.      (new))
  1277.     (save-excursion
  1278.       (while (/= count 0)
  1279.     (let ((depth (if up-flag 0 -1)) found)
  1280.       (save-excursion
  1281.         ;; Find the "next" significant line in the proper direction.
  1282.         (while (and (not found)
  1283.             ;; Rather than searching for a # sign that comes
  1284.             ;; at the beginning of a line aside from whitespace,
  1285.             ;; search first for a string starting with # sign.
  1286.             ;; Then verify what precedes it.
  1287.             ;; This is faster on account of the fastmap feature of
  1288.             ;; the regexp matcher.
  1289.             (funcall search-function
  1290.                  "#[ \t]*\\(if\\|elif\\|endif\\)"
  1291.                  nil t))
  1292.           (beginning-of-line)
  1293.           ;; Now verify it is really a preproc line.
  1294.           (if (looking-at "^[ \t]*#[ \t]*\\(if\\|elif\\|endif\\)")
  1295.           (let ((prev depth))
  1296.             ;; Update depth according to what we found.
  1297.             (beginning-of-line)
  1298.             (cond ((looking-at "[ \t]*#[ \t]*endif")
  1299.                (setq depth (+ depth increment)))
  1300.               ((looking-at "[ \t]*#[ \t]*elif")
  1301.                (if (and forward (= depth 0))
  1302.                    (setq found (point))))
  1303.               (t (setq depth (- depth increment))))
  1304.             ;; If we are trying to move across, and we find
  1305.             ;; an end before we find a beginning, get an error.
  1306.             (if (and (< prev 0) (< depth prev))
  1307.             (error (if forward
  1308.                    "No following conditional at this level"
  1309.                  "No previous conditional at this level")))
  1310.             ;; When searching forward, start from next line
  1311.             ;; so that we don't find the same line again.
  1312.             (if forward (forward-line 1))
  1313.             ;; If this line exits a level of conditional, exit inner loop.
  1314.             (if (< depth 0)
  1315.             (setq found (point)))))))
  1316.       (or found
  1317.           (error "No containing preprocessor conditional"))
  1318.       (goto-char (setq new found)))
  1319.     (setq count (+ count increment))))
  1320.     (push-mark)
  1321.     (goto-char new)))
  1322.  
  1323. ;;; c-mode.el ends here
  1324.